home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / checkbox / variables.py < prev   
Text File  |  2009-11-05  |  8KB  |  279 lines

  1. #
  2. # This file is part of Checkbox.
  3. #
  4. # Copyright 2008 Canonical Ltd.
  5. #
  6. # Checkbox is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # Checkbox is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Checkbox.  If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. import re
  20. import posixpath
  21.  
  22. from checkbox.lib.text import split
  23.  
  24.  
  25. def raise_none_error(attribute):
  26.     if not attribute:
  27.         raise ValueError("None isn't acceptable as a value")
  28.     else:
  29.         name = attribute.name
  30.         raise ValueError("None isn't acceptable as a value for %s" % name)
  31.  
  32.  
  33. # Implementation of partial function in Python 2.5+
  34. def VariableFactory(cls, **old_kwargs):
  35.     def variable_factory(**new_kwargs):
  36.         kwargs = old_kwargs.copy()
  37.         kwargs.update(new_kwargs)
  38.         return cls(**kwargs)
  39.  
  40.     return variable_factory
  41.  
  42. try:
  43.     from functools import partial as VariableFactory
  44. except ImportError:
  45.     pass
  46.  
  47.  
  48. class Variable(object):
  49.  
  50.     _value = None
  51.     _required = True
  52.  
  53.     attribute = None
  54.  
  55.     def __init__(self, attribute=None, value=None, value_factory=None,
  56.                  required=True):
  57.         self.attribute = attribute
  58.         self._required = required
  59.         if value is not None:
  60.             self.set(value)
  61.         if value_factory is not None:
  62.             self.set(value_factory())
  63.  
  64.     def get(self):
  65.         if self._value is None and self._required is True:
  66.             raise_none_error(self.attribute)
  67.  
  68.         return self._value
  69.  
  70.     def set(self, value):
  71.         if value is None:
  72.             if self._required is True:
  73.                 raise_none_error(self.attribute)
  74.  
  75.             new_value = None
  76.         else:
  77.             new_value = self.coerce(value)
  78.  
  79.         self._value = new_value
  80.  
  81.     def coerce(self, value):
  82.         return value
  83.  
  84.  
  85. class ConstantVariable(Variable):
  86.     __slots__ = ("_item_factory")
  87.  
  88.     def __init__(self, item_factory, *args, **kwargs):
  89.         self._item_factory = item_factory
  90.         super(ConstantVariable, self).__init__(*args, **kwargs)
  91.  
  92.     def coerce(self, value):
  93.         if self._value is not None and value != self._value:
  94.             raise ValueError("%r != %r" % (value, self._value))
  95.         return self._item_factory(value=value).get()
  96.  
  97.  
  98. class BoolVariable(Variable):
  99.     __slots__ = ()
  100.  
  101.     def coerce(self, value):
  102.         if isinstance(value, str):
  103.             if re.match(r"(yes|true)", value, re.IGNORECASE):
  104.                 value = True
  105.             elif re.match(r"(no|false)", value, re.IGNORECASE):
  106.                 value = False
  107.             else:
  108.                 raise ValueError("%r is not a bool string" % (value,))
  109.         elif not isinstance(value, bool):
  110.             raise ValueError("%r is not a bool" % (value,))
  111.  
  112.         return value
  113.  
  114.  
  115. class StringVariable(Variable):
  116.     __slots__ = ()
  117.  
  118.     def coerce(self, value):
  119.         if not isinstance(value, str):
  120.             raise ValueError("%r is not a str" % (value,))
  121.  
  122.         return value
  123.  
  124.  
  125. class PathVariable(StringVariable):
  126.     __slots__ = ()
  127.  
  128.     def coerce(self, value):
  129.         path = super(PathVariable, self).coerce(value)
  130.         return posixpath.expanduser(path)
  131.  
  132.  
  133. class UnicodeVariable(Variable):
  134.     __slots__ = ()
  135.  
  136.     def coerce(self, value):
  137.         if isinstance(value, str):
  138.             value = unicode(value)
  139.         elif not isinstance(value, unicode):
  140.             raise ValueError("%r is not a unicode" % (value,))
  141.  
  142.         return value
  143.  
  144.  
  145. class IntVariable(Variable):
  146.     __slots__ = ()
  147.  
  148.     def coerce(self, value):
  149.         if isinstance(value, str):
  150.             value = int(value)
  151.         elif not isinstance(value, (int, long)):
  152.             raise ValueError("%r is not an int nor long" % (value,))
  153.  
  154.         return value
  155.  
  156.  
  157. class FloatVariable(Variable):
  158.     __slots__ = ()
  159.  
  160.     def coerce(self, value):
  161.         if isinstance(value, str):
  162.             value = float(value)
  163.         elif not isinstance(value, (int, long, float)):
  164.             raise ValueError("%r is not a float" % (value,))
  165.  
  166.         return value
  167.  
  168.  
  169. class ListVariable(Variable):
  170.     __slots__ = ("_item_factory", "_separator")
  171.  
  172.     def __init__(self, item_factory, separator, *args, **kwargs):
  173.         self._item_factory = item_factory
  174.         self._separator = separator
  175.         super(ListVariable, self).__init__(*args, **kwargs)
  176.  
  177.     def coerce(self, values):
  178.         item_factory = self._item_factory
  179.         if isinstance(values, str):
  180.             values = split(values, self._separator) if values else []
  181.         elif not isinstance(values, (list, tuple)):
  182.             raise ValueError("%r is not a list or tuple" % (values,))
  183.  
  184.         return [item_factory(value=v).get() for v in values]
  185.  
  186.  
  187. class TupleVariable(ListVariable):
  188.  
  189.     def coerce(self, values):
  190.         values = super(TupleVariable, self).coerce(values)
  191.         return tuple(values)
  192.  
  193.  
  194. class AnyVariable(Variable):
  195.     __slots__ = ("_schemas")
  196.  
  197.     def __init__(self, schemas, *args, **kwargs):
  198.         self._schemas = schemas
  199.         super(AnyVariable, self).__init__(*args, **kwargs)
  200.  
  201.     def coerce(self, value):
  202.         for schema in self._schemas:
  203.             try:
  204.                 # Only check that the value can be coerced
  205.                 dummy = schema(value=value).get()
  206.                 return value
  207.             except ValueError:
  208.                 pass
  209.  
  210.         raise ValueError("%r did not match any schema" % value)
  211.  
  212.  
  213. class DictVariable(Variable):
  214.     __slots__ = ("_key_schema", "_value_schema")
  215.  
  216.     def __init__(self, key_schema, value_schema, *args, **kwargs):
  217.         self._key_schema = key_schema
  218.         self._value_schema = value_schema
  219.         super(DictVariable, self).__init__(*args, **kwargs)
  220.  
  221.     def coerce(self, value):
  222.         if not isinstance(value, dict):
  223.             raise ValueError("%r is not a dict." % (value,))
  224.         new_dict = {}
  225.         for k, v in value.items():
  226.             new_dict[self._key_schema(value=k).get()] = \
  227.                 self._value_schema(value=v).get()
  228.         return new_dict
  229.  
  230.  
  231. class MapVariable(Variable):
  232.     __slots__ = ("_schema")
  233.  
  234.     def __init__(self, schema, *args, **kwargs):
  235.         self._schema = schema
  236.         super(MapVariable, self).__init__(*args, **kwargs)
  237.  
  238.     def coerce(self, value):
  239.         if not isinstance(value, dict):
  240.             raise ValueError("%r is not a dict." % (value,))
  241.  
  242.         for k, v in value.iteritems():
  243.             if k not in self._schema:
  244.                 raise ValueError("%r is not a valid key as per %r"
  245.                                    % (k, self._schema))
  246.  
  247.         new_dict = {}
  248.         for attribute, variable in self._schema.iteritems():
  249.             old_value = value.get(attribute)
  250.             try:
  251.                 new_value = variable(value=old_value).get()
  252.             except ValueError, e:
  253.                 raise ValueError(
  254.                     "Value of %r key of dict %r could not be converted: %s"
  255.                     % (attribute, value, e))
  256.  
  257.             if attribute in value:
  258.                 new_dict[attribute] = new_value
  259.  
  260.         return new_dict
  261.  
  262.  
  263. def get_variable(obj, attribute):
  264.     return get_variables(obj)[attribute]
  265.  
  266. def get_variables(obj):
  267.     from checkbox.attribute import get_attributes
  268.  
  269.     if "__checkbox_variables__" in obj.__dict__:
  270.         return obj.__dict__["__checkbox_variables__"]
  271.     else:
  272.         variables = {}
  273.         cls = type(obj)
  274.         for attribute in get_attributes(cls).itervalues():
  275.             variable = attribute.variable_factory(attribute=attribute)
  276.             variables[attribute] = variable
  277.  
  278.         return obj.__dict__.setdefault("__checkbox_variables__", variables)
  279.